package com.yonyou.cyxdms.basedata.service.config.annotation ;

import com.alibaba.fastjson.JSON;
import com.yonyou.cyxdms.basedata.service.service.sap.DealerToSapService;
import com.yonyou.cyxdms.basedata.service.service.sap.DealerToSapServiceImpl;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.PrintWriter;
import java.io.StringWriter;

@Aspect
@Component
@Slf4j
public class InterfaceLogAspect {

    @Autowired
    DealerToSapService dealerToSapService;

    @Pointcut("@annotation(com.yonyou.cyxdms.basedata.service.config.annotation.InterfaceLog)")
    public void logPointCut() {
        System.out.println("进入接口日志aop");
    }

    @Around(value = "logPointCut()")
    public Object doAround(ProceedingJoinPoint joinPoint) {
        Object responseBody = null;
        Long logId = 0L;
        String batchNo = null;
        String interfaceNo = null;
        Object requestBody = null;
        try {

            Object[] args = joinPoint.getArgs();
            batchNo = (String) args[0];
            interfaceNo = (String) args[1];
            requestBody = args[2];
            log.info("批次号:{},请求编号:{},请求参数：{}", batchNo, interfaceNo, JSON.toJSONString(requestBody));
            logId = dealerToSapService.saveLog(batchNo, interfaceNo, requestBody, null, null);

            responseBody = joinPoint.proceed(args);
            log.info("批次号:{},请求编号:{},返回参数：{}", batchNo, interfaceNo, JSON.toJSONString(responseBody));
            dealerToSapService.updateLog(logId, responseBody, null);

        } catch (Throwable e) {
            log.error("批次号:{},请求编号:{},异常信息：{}", batchNo, interfaceNo, getStackTrace(e));
            dealerToSapService.updateLog(logId, responseBody, e);
            return null;

        }

        return responseBody;

    }

    /**
     * 获取完整的异常信息
     *
     * @param throwable
     * @return
     */
    public static String getStackTrace(Throwable throwable) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        try {
            throwable.printStackTrace(pw);
            return String.valueOf(sw);
        } finally {
            pw.close();
        }
    }

}

